<?php
/**
 * @file : relationtype.php
 * @date : 2015-01-04
 */
namespace haibao\cms\data;

use \haibao\frame\data\query\Condition;
use haibao\cms\model\filter\RelationType as RelationTypeFilter;
use haibao\cms\model\data\RelationType as RelationTypeModel;

class RelationType extends \haibao\cms\data\BaseMysql{

    public function __construct(){
        parent::__construct('\haibao\cms\model\data\RelationType');
    }
    
    /**
     * 根据关系类型名字获取类型ID
     * @param : String $typeName 
     */
    public function getTypeByTypeName($typeName){
    	
    	$filter = new RelationTypeFilter;
    	$filter->select(array(
            RelationTypeFilter::CONDITION_FIELD_NAME_ID,         
            RelationTypeFilter::CONDITION_FIELD_NAME_TYPE_NAME,         
        ));
    	$filter->where(RelationTypeFilter::CONDITION_FIELD_NAME_TYPE_NAME,Condition::CONDITION_EQUAL,$typeName);
    	$data = $this->getOne($filter);
    	if(empty($data)){
    		return $this->addRelationTypeByTypeName($typeName);
        }else{
            return $data->Id;
        }
    }
    
    /**
     * 根据类型名字添加一条关系类型
     * @param : String $typeName 
     */
    public function addRelationTypeByTypeName($typeName, $status = \haibao\cms\model\data\RelationType::STATUS_ENABLE){
    	
    	$model = new RelationTypeModel();
    	$model->TypeName = $typeName;
    	$model->Status = 1;
        $this->add($model);
    	return $model->Id;
    }
    
    /**
     * 获取所有的关系类型
     */
    public function getRelationType(){
    	
    	$filter = new RelationTypeFilter;
    	$filter->select(array(
    			RelationTypeFilter::CONDITION_FIELD_NAME_ID,
    			RelationTypeFilter::CONDITION_FIELD_NAME_TYPE_NAME,
    	));
    	return $this->getAll($filter);
    
    }
    
    public function getRelationNameByRelId($relId){
    	$filter = new RelationTypeFilter;
    	$filter->select(array(
    			RelationTypeFilter::CONDITION_FIELD_NAME_TYPE_NAME,
    	));
    	$filter->where(RelationTypeFilter::CONDITION_FIELD_NAME_ID,Condition::CONDITION_EQUAL,$relId);
    	$filter->where(RelationTypeFilter::CONDITION_FIELD_NAME_STATUS,Condition::CONDITION_EQUAL,\haibao\cms\model\data\RelationType::STATUS_ENABLE);
    	$data = $this->getOne($filter);
    	if($data){
    		return $data->TypeName;
    	}else{
    		return '';
    	}
    }
}
